

export default class Utils {

    /**
     * @param delay 时长，单位s
     * @returns 
     */
    public static async wait(delay: number) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(true);
            }, delay * 1000);
        });
    }

    /**
     * 等完成
     * @param onComplete
     * @returns 
     */
    public static async waitDone(onComplete: Function, target: any) {
        return new Promise((resolve, reject) => {
            let id = setInterval(() => {
                if (onComplete.call(target)) {
                    clearInterval(id);
                    resolve(true);
                }
            }, 50);
        });
    }


    /**
     * 图片压缩
     * @param image 
     * @param width 
     * @param height 
     * @returns 
     */
    public static imageScale(image: HTMLImageElement, width: number, height: number): HTMLImageElement | null {
        const canvas = document.createElement('canvas');
        const context = canvas.getContext('2d');
        if (!context) {
            return null;
        }

        canvas.width = width;
        canvas.height = height;
        context.clearRect(0, 0, width, height);
        context.drawImage(image, 0, 0, width, height);

        var _image = new Image();
        _image.src = canvas.toDataURL("image/png");
        _image.width = width;
        _image.height = height;
        // document.removeChild(canvas);
        return _image;
    }
}